package com.example.literj.kt.android.schedulers

import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.Message
import com.example.literj.kt.android.plugins.RxAndroidPlugins
import com.example.literj.kt.core.Scheduler

class AndroidSchedulers {
    companion object {
        private object MainHolder {
            val DEFAULT = internalFrom(Looper.getMainLooper(), true)
        }

        private val MAIN_THREAD: Scheduler =
            RxAndroidPlugins.initScheduler { MainHolder.DEFAULT }

        @JvmStatic
        fun mainThread(): Scheduler {
            return RxAndroidPlugins.onMainThreadScheduler(MAIN_THREAD)
        }

        private fun internalFrom(looper: Looper, async: Boolean): Scheduler {
            var isAsync = async
            if (Build.VERSION.SDK_INT < 16) {
                isAsync = false
            } else if (isAsync && Build.VERSION.SDK_INT < 22) {
                val message = Message.obtain()
                try {
                    message.isAsynchronous = true
                } catch (e: NoSuchMethodError) {
                    isAsync = false
                }
                message.recycle()
            }
            return HandlerScheduler(Handler(looper), isAsync)
        }
    }
}